package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.DTO.ClueQueryDTO;
import com.crm.DTO.FishCluesDTO;
import com.crm.common.exception.BusinessException;
import com.crm.common.result.TableDataInfo;
import com.crm.common.utils.ThreadLocalUtil;
import com.crm.controller.BaseController;
import com.crm.entity.Business;
import com.crm.entity.Clue;
import com.crm.entity.system.SysUser;
import com.crm.mapper.ClueMapper;
import com.crm.mapper.system.SysUserMapper;
import com.crm.service.BusinessService;
import com.crm.service.ClueService;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chy
 * @description 针对表【clue(线索表)】的数据库操作Service实现
 * @createDate 2025-09-04 13:20:18
 */
@Service
@Slf4j
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private BusinessService businessService;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 分页查询
     *
     * @param queryDTO
     * @return
     */
    @Override
    public TableDataInfo<Clue> pageCules(ClueQueryDTO queryDTO) {
        Page<Clue> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        LambdaQueryWrapper<Clue> queryWrapper = new LambdaQueryWrapper<Clue>()
                .eq(queryDTO.getId() != null, Clue::getId, queryDTO.getId())
                .eq(queryDTO.getPhone() != null, Clue::getPhone, queryDTO.getPhone())
                .like(queryDTO.getOwner() != null, Clue::getOwner, queryDTO.getOwner())
                .like(StringUtils.hasText(queryDTO.getStatus()), Clue::getStatus, queryDTO.getStatus())
                .eq(queryDTO.getChannel() != null, Clue::getChannel, queryDTO.getChannel())
                .ge(queryDTO.getBeginCreateTime() != null, Clue::getCreateTime, queryDTO.getBeginCreateTime())
                .le(queryDTO.getEndCreateTime() != null, Clue::getUpdateTime, queryDTO.getEndCreateTime())
                // 明确处理 NULL 值情况
                .and(wrapper -> wrapper.isNull(Clue::getTransfer).or().ne(Clue::getTransfer, 1))
                .orderByDesc(Clue::getUpdateTime); //排序

        Page<Clue> cluePage = this.page(page, queryWrapper);

        return new BaseController().getDataTable(cluePage);
    }

    /**
     * 保存线索
     *
     * @param clue
     */
    @Override
    public void saveClue(Clue clue) {
        Long userId = ThreadLocalUtil.getUserId();
        clue.setUserId(Integer.valueOf(userId.toString()));
        super.save(clue);
    }

    /**
     * 修改伪线索,放进线索池
     *
     * @param clue
     * @return
     */
    @Override
    public boolean updatePseudoById(Long id, Clue clue) {
        Clue clueOdd = super.getById(id);
        if (clueOdd == null) {
            return false;
        }
        //删除线索逻辑
        Long falseCount = clueOdd.getFalseCount();
        Long count = falseCount == null ? 1 : falseCount + 1;
        // pseudos 第大于3次删除线索
        if (count == 4) {
            //删除线索
            return super.removeById(id);
        }
        // 转到线索池
        if (!StringUtils.hasText(clue.getRemark())) {
            throw new BusinessException("请填写备注");
        }
        clueOdd.setRemark(clue.getRemark());
        clueOdd.setTransfer(1);//转移到线索池

        clueOdd.setFalseCount(count);
        return super.updateById(clueOdd);

    }

    /**
     * 分页查询线索池
     *
     * @return
     */
    @Override
    public TableDataInfo<Clue> getCluePool(ClueQueryDTO queryDTO) {

        Page<Clue> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        LambdaQueryWrapper<Clue> queryWrapper = new LambdaQueryWrapper<Clue>()
                .eq(queryDTO.getId() != null, Clue::getId, queryDTO.getId())
                .eq(queryDTO.getPhone() != null, Clue::getPhone, queryDTO.getPhone())
                .eq(queryDTO.getChannel() != null, Clue::getChannel, queryDTO.getChannel())
                .ge(queryDTO.getBeginCreateTime() != null, Clue::getCreateTime, queryDTO.getBeginCreateTime())
                .le(queryDTO.getEndCreateTime() != null, Clue::getUpdateTime, queryDTO.getEndCreateTime())
                .eq(Clue::getTransfer, 1)
                .orderByDesc(Clue::getUpdateTime);

        Page<Clue> cluePage = this.page(page, queryWrapper);
        return new BaseController().getDataTable(cluePage);
    }

    /**
     * 批量捞取线索
     *
     * @param fishCluesDTO
     * @return
     */
    @Override
    @Transactional
    public boolean updateFishWithById(FishCluesDTO fishCluesDTO) {

        List<Integer> ids = fishCluesDTO.getIds();//拿到线索id集合
        //获取到ids的长度
        if (ids.size() > 3) {
            throw new BusinessException("一次最多捞取3条线索");
        }
        //批量查询
        List<Clue> clues = super.listByIds(ids);
        if (CollectionUtils.isEmpty(clues)) {
            return false;
        }

        List<Clue> collect = clues.stream().map(clue -> {
            clue.setUserId(fishCluesDTO.getUserId()); //设置用户id
            clue.setStatus("1");
            clue.setTransfer(null);
            clue.setReason(null);
            clue.setRemark(null);
            return clue;
        }).collect(Collectors.toList());
        return super.updateBatchById(collect);
    }

    /**
     * 线索转换为商机
     *
     * @param id
     * @return
     */
    @Override
    public boolean changeBusiness(Long id) {
        Clue clue = super.getById(id);
        if (clue == null) {
            throw new BusinessException("线索不存在");
        }

        Business business = new Business();
        BeanUtil.copyProperties(clue, business);
        business.setStatus(1);
        business.setClueId(id);//线索id
        log.info("线索转换为商机：{}", business);

        //TODO:线索转商机不知道是否删除线索
        boolean result = businessService.save(business);
        return result;
    }

    @Override
    public void assignment(Long ownerId, Long transferId) {
        //参数校验
        if (ownerId == null || transferId == null) {
            throw new BusinessException("参数错误");
        }
        if (ownerId.equals(transferId)) {
            throw new BusinessException("不能转让给自己");
        }
        //获取当前拥有有人
        SysUser owner = sysUserMapper.selectUserById(ownerId);
        //转派目标
        SysUser transfer = sysUserMapper.selectUserById(transferId);
        //获取当前所有人的线索
        List<Clue> clues = super.list(new LambdaQueryWrapper<Clue>()
                .eq(Clue::getOwner, owner.getUserName()));
        clues.forEach(clue -> clue.setOwner(transfer.getUserName()));
        super.updateBatchById(clues);
    }
}




